<?php

namespace App\Admin\Livewire;

use Dcat\Admin\Admin;
use Illuminate\Contracts\View\View;
use Illuminate\Notifications\DatabaseNotification;
use Livewire\Attributes\On;
use Livewire\Component;

class Notifications extends Component
{
    public $count;

    public $notifications = [];

    public $enable = false;

    public function mount(): void
    {
        if ($this->enable) {
            $this->count = Admin::user()->unreadNotifications()->count();
            $this->setNotificationData();
        }
    }

    private function setNotificationData(): void
    {
        $this->notifications = Admin::user()->unreadNotifications()->limit(5)->get();
    }

    public function refreshAdminNotificationCount(): void
    {
        $count = Admin::user()->unreadNotifications()->count();

        if ($count != $this->count) {
            $this->count = $count;
            $this->setNotificationData();
        }
    }

    public function readOne(string $id): void
    {
        $notification = DatabaseNotification::find($id);
        $notification->markAsRead();

        $this->count = Admin::user()->unreadNotifications()->count();
        $this->setNotificationData();
    }

    #[On('mark-all')]
    public function markAll(): void
    {
        Admin::user()->unreadNotifications->markAsRead();
        $this->count = 0;
        $this->notifications = [];
        $this->dispatch('mark-readed', message: '标记已读成功');
    }

    public function render(): View|string
    {
        if ($this->enable) {
            return view('admin.notification');
        }

        return <<<'HTML'
            <div>
            </div>
            HTML;
    }
}
